
TOOL.Category		= "Airships"
TOOL.Name			= "Sky Titans Spawn Tool"
TOOL.Command		= nil
TOOL.ConfigName		= ""

include("sky_titans/shared/st_spawntool_list.lua")
include("sky_titans/shared/st_weapons.lua")

local weaponmodels = {}
for model, tbl in pairs( st_weapons ) do
    table.insert(weaponmodels,model)
end

cleanup.Register("st_boiler")
cleanup.Register("st_weapon")
cleanup.Register("st_fan")
cleanup.Register("st_balloon")

TOOL.ClientConVar =
{
	// Tool menu options
	class			        = "",
    model               = "",
    spawnfrozen         = 0,
    spawnweld           = 0
}

if(SERVER) then

    CreateConVar("sbox_max_st_boiler", 1)
    CreateConVar("sbox_max_st_weapon", 12)
    CreateConVar("sbox_max_st_fan", 8)
    CreateConVar("sbox_max_st_balloon", 4)
    
    function MoveOrient( class, ent, tr )
        if(class=="st_fan") then
            local max = ent:OBBMaxs()
            local min = ent:OBBMins()
            local width = math.abs(max.x-min.x)
            local height = math.abs(max.y-min.y)
            local depth = math.abs(max.z-min.z)
            
            if(width<height and width<depth) then
                ent:SetPos( tr.HitPos - tr.HitNormal * ent:OBBMins().x )
                ent:SetAngles( tr.HitNormal:Angle() + Angle(0,0,0) )
            elseif(height<width and height<depth) then
                ent:SetPos( tr.HitPos - tr.HitNormal * ent:OBBMins().y )
                ent:SetAngles( tr.HitNormal:Angle() + Angle(0,0,90) )
            else
                ent:SetPos( tr.HitPos - tr.HitNormal * ent:OBBMins().z )
                ent:SetAngles( tr.HitNormal:Angle() + Angle(90,0,0) )
            end
            
            if(ent:GetModel()=="models/props_phx/misc/propeller2x_small.mdl") then
                ent:SetPos( tr.HitPos - tr.HitNormal * ent:OBBMins().z )
                ent:SetAngles( tr.HitNormal:Angle() + Angle(90,0,0) ) 
            end
        else
            ent:SetPos( tr.HitPos - tr.HitNormal * ent:OBBMins().z )
            ent:SetAngles( tr.HitNormal:Angle() + Angle(90,0,0) )
        end
    end

    function TOOL:LeftClick( tr )

        if (!tr) then return end
        local ply = self:GetOwner()
        
        ply:SetNetworkedInt("st_money", 1000000 )
        ply:ConCommand( "st_moneyhud 1" )
        
        local spawnclass = self:GetClientInfo("class")
        local spawnmodel = self:GetClientInfo("model")
        local spawnfreeze = self:GetClientNumber("spawnfrozen")
        local spawnweld = self:GetClientNumber("spawnweld")

        local st_classes = {"st_weapon","st_boiler","st_fan","st_balloon"}
        if( !table.HasValue( st_classes , spawnclass ) ) then return false end
        if(not ply:CheckLimit("_"..spawnclass)) then return false end
        if( spawnclass=="st_boiler" and !table.HasValue( boilermodels , spawnmodel ) ) then return false end
        if( spawnclass=="st_weapon" and !table.HasValue( weaponmodels , spawnmodel ) ) then return false end
        if( spawnclass=="st_fan" and !table.HasValue( fanmodels , spawnmodel ) ) then return false end
        if( spawnclass=="st_balloon" and !table.HasValue( balloonmodels , spawnmodel ) ) then return false end

            local ent = ents.Create( spawnclass )
            ent:SetModel( spawnmodel )
            MoveOrient( spawnclass, ent, tr )
            ent.Owner = ply
            ent:Activate()
            ent:Spawn()
            
            print(ply:GetName().." ("..ply:SteamID()..") spawned "..tostring(ent))
            
            local phys = ent:GetPhysicsObject()
            if(phys:IsValid()) then phys:EnableMotion( spawnfreeze==0 ) end
            
            undo.Create( spawnclass )
            undo.AddEntity( ent )
            if (spawnweld==1 and !tr.Entity:IsWorld() and !tr.Entity:IsPlayer()) then
                local weld = constraint.Weld( ent, tr.Entity, 0, tr.PhysicsBone, 0 )
                local nocollide = constraint.NoCollide( ent, tr.Entity, 0, tr.PhysicsBone )
                undo.AddEntity( weld )
                undo.AddEntity( nocollide )
            end
            undo.SetPlayer( ply )
            undo.Finish()
            
            return true
        
    end

    function TOOL:Think()
        local tr = self:GetOwner():GetEyeTrace()
            if(self.ghost and self.ghost:IsValid()) then
                MoveOrient( self:GetClientInfo("class"), self.ghost, tr )
                self.ghost:SetModel(self:GetClientInfo("model"))
            else
                self.ghost = ents.Create("gmod_ghost")
                self.ghost:SetModel(self:GetClientInfo("model"))
                self.ghost:SetColor(Color(64,255,64,255))
            end
    end
        
    function TOOL:Holster()
        if(self.ghost and self.ghost:IsValid()) then self.ghost:Remove() end
    end

end

if CLIENT then
	language.Add("Tool.st_spawntool.name", TOOL.Name)
	language.Add("Tool.st_spawntool.desc", "Spawn Sky Titans weapons and modules")
	language.Add("Tool.st_spawntool.0", "Left Click to spawn")
    language.Add("Undone_st_boiler", "Undone Airship Boiler")
    language.Add("Undone_st_weapon", "Undone Airship Weapon")
    language.Add("Undone_st_fan", "Undone Airship Propeller")
    language.Add("Undone_st_balloon", "Undone Airship Balloon")
    language.Add("SBoxLimit__st_boiler", "Hit Max Airship Boiler Limit!")
    language.Add("SBoxLimit__st_weapon", "Hit Max Airship Weapon Limit!")
    language.Add("SBoxLimit__st_fan", "Hit Max Airship Propeller Limit!")
    language.Add("SBoxLimit__st_balloon", "Hit Max Airship Balloon Limit!")
    
	function TOOL.BuildCPanel( CPanel )
    
        SpawnLabel = vgui.Create("DLabel")
        SpawnLabel:SetFont("default")
        SpawnLabel:SetColor(Color(32,32,128,255)) // Color
        SpawnLabel:SetText("")
        SpawnLabel:SizeToContents()
        CPanel:AddItem( SpawnLabel )
    
        local CategoryBoilers = vgui.Create( "DCollapsibleCategory" )
                CategoryBoilers:SetLabel( "Boilers" )
                CategoryBoilers:SetExpanded( 0 )

                local BoilerList   = vgui.Create( "DIconLayout" , CategoryBoilers)
                BoilerList:SetSpaceY( 4 )
                BoilerList:SetSpaceX( 4 )

                for n, model in pairs( boilermodels ) do
                    local icon = BoilerList:Add( "SpawnIcon" )
                    icon.dmodel = model
                    icon:SetModel( icon.dmodel )
                    icon.DoClick = function( button )
                        RunConsoleCommand("st_spawntool_model", button.dmodel)
                        RunConsoleCommand("st_spawntool_class", "st_boiler")
                        SpawnLabel:SetText("Boiler: "..string.sub(button.dmodel,7))
                    end
                end  

                CategoryBoilers:SetContents( BoilerList )
                
        CPanel:AddItem( CategoryBoilers )
        
        local CategoryWeapons = vgui.Create( "DCollapsibleCategory" )
                CategoryWeapons:SetLabel( "Weapons" )
                CategoryWeapons:SetExpanded( 0 )

                local WeaponList   = vgui.Create( "DIconLayout" , CategoryWeapons)
                WeaponList:SetSpaceY( 4 )
                WeaponList:SetSpaceX( 4 )

                for model, tbl in pairs( st_weapons ) do
                    local icon = WeaponList:Add( "SpawnIcon" )
                    icon.dmodel = model
                    icon.dname = tbl.name
                    icon:SetModel( icon.dmodel )
                        local txt = tbl.name.."\nDamage: "..tbl.damage
                        if(tbl.barrels and tbl.barrels>1) then txt = txt.."x"..tbl.barrels end
                        if(tbl.clip and tbl.rate) then txt = txt.."\nMagazine Size: "..tbl.clip.."\nFire Rate: "..tbl.rate end
                        txt = txt.."\nReload Time: "..tbl.reload.." secs.\nField: "..(tbl.field[1]*2).." horiz. / "..tbl.field[3].." ~ "..tbl.field[2].." vert."
                        icon:SetToolTip(txt)
                    icon.DoClick = function( button )
                        RunConsoleCommand("st_spawntool_model", button.dmodel)
                        RunConsoleCommand("st_spawntool_class", "st_weapon")
                        SpawnLabel:SetText("Weapon: "..button.dname)
                    end
                end  

                CategoryWeapons:SetContents( WeaponList )
                
        CPanel:AddItem( CategoryWeapons )
        
        local CategoryBalloons = vgui.Create( "DCollapsibleCategory" )
                CategoryBalloons:SetLabel( "Balloons" )
                CategoryBalloons:SetExpanded( 0 )

                local BalloonList   = vgui.Create( "DIconLayout" , CategoryBalloons)
                BalloonList:SetSpaceY( 0 )
                BalloonList:SetSpaceX( 0 )

                for n, model in pairs( balloonmodels ) do
                    local icon = BalloonList:Add( "SpawnIcon" )
                    icon.dmodel = model
                    icon:SetModel( icon.dmodel )
                    icon.DoClick = function( button )
                        RunConsoleCommand("st_spawntool_model", button.dmodel)
                        RunConsoleCommand("st_spawntool_class", "st_balloon")
                        SpawnLabel:SetText("Balloon: "..string.sub(button.dmodel,7))
                    end
                end  

                CategoryBalloons:SetContents( BalloonList )
                
        CPanel:AddItem( CategoryBalloons )
        
        local CategoryFans = vgui.Create( "DCollapsibleCategory" )
                CategoryFans:SetLabel( "Propellers" )
                CategoryFans:SetExpanded( 0 )

                local FanList   = vgui.Create( "DIconLayout" , CategoryFans)
                FanList:SetSpaceY( 0 )
                FanList:SetSpaceX( 0 )

                for n, model in pairs( fanmodels ) do
                    local icon = FanList:Add( "SpawnIcon" )
                    icon.dmodel = model
                    icon:SetModel( icon.dmodel )
                    icon.DoClick = function( button )
                        RunConsoleCommand("st_spawntool_model", button.dmodel)
                        RunConsoleCommand("st_spawntool_class", "st_fan")
                        SpawnLabel:SetText("Propeller: "..string.sub(button.dmodel,7))
                    end
                end  

                CategoryFans:SetContents( FanList )
                
        CPanel:AddItem( CategoryFans )
        
        local CheckboxFrozen = vgui.Create( "DCheckBoxLabel" )
        CheckboxFrozen:SetText( "Spawn Frozen" )
        CheckboxFrozen:SetConVar( "st_spawntool_spawnfrozen" )
        CheckboxFrozen:SetValue( 0 )
        CheckboxFrozen:SizeToContents() 
        CPanel:AddItem( CheckboxFrozen )
        
        local CheckboxWeld = vgui.Create( "DCheckBoxLabel" )
        CheckboxWeld:SetText( "Weld" )
        CheckboxWeld:SetConVar( "st_spawntool_spawnweld" )
        CheckboxWeld:SetValue( 0 )
        CheckboxWeld:SizeToContents() 
        CPanel:AddItem( CheckboxWeld )
    
	end
end